<%@ page isELIgnored="false" %>

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <!-- web路径：
    不以/开始的相对路径，找资源，以当前资源的路径为基准，经常容易出问题。
    以/开始的相对路径，找资源，以服务器的路径为标准(http://localhost:3306)；需要加上项目名
            http://localhost:3306/crud
     -->

    <script type="text/javascript"
            src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
    <link
            href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
            rel="stylesheet">
    <script
            src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<!-- 修改员工模态框 -->
<div class="modal fade" id="empUpdateModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">

                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_update"></p>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_update_input"
                                   placeholder="email@google.com">
                            <span class="help-block"></span>
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_update_input" value="M"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
                            </label>
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="dId">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="update_emp_button">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加员工模态框 -->

<div class="modal fade" id="empAddModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">

                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="empName_add_input"
                                   placeholder="empName">
                            <span class="help-block">.</span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_add_input"
                                   placeholder="email@google.com">
                            <span class="help-block">.</span>

                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_add_input" value="M"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
                            </label>
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="dept_select" name="dId">

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="save_emp_button">保存</button>
            </div>
        </div>
    </div>
</div>

<%--    搭建显示页面--%>
<div class="container">
    <%--    标题--%>
    <div class="row">
        <div class="col-md12">
            <h1>SSM增删改查</h1>
        </div>
    </div>


    <%--    按钮--%>
    <div class="row">
        <div class=" col-md-4  col-md-offset-8">


            <!-- Button trigger modal -->
            <button class="btn btn-primary" id="empAdd_add_btn">新增</button>
            <button class="btn btn-danger" id="del_emp_all_btn">删除</button>
        </div>
    </div>
    <%--    显示表格数据--%>
    <div class="row">
        <div class="col-md-12">

            <table class="table table-hover" id="emps_teble">
                <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="check_all">
                    </th>
                    <th>#</th>
                    <th>empName</th>
                    <th>gender</th>
                    <th>email</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>


                </tbody>
            </table>
        </div>
    </div>
    <%--    分页信息--%>
    <div class="row">
        <%--    分页文字信息--%>
        <div class="col-md-6" id="page_info_area">
        </div>
        <%--        分页条信息--%>
        <div class="col-md-6" id="page_nav_area">

        </div>

    </div>

</div>
</body>

<script type="text/javascript">
    var totalRcode, currentPage;

    $(function () {
        toPage(1);
    });


    //查询某一页
    function toPage(pn) {
        $.ajax({
            url: "${APP_PATH}/emps",
            data: "pn=" + pn,
            type: "GET",
            success: function (result) {
                console.log(result);
                //      1.解析员工数据
                build_emps_table(result);
                //     2.解释分页数据

                build_page_info(result);

                build_page_nav(result);
            }
        });
    }

    function build_emps_table(result) {
        //掏空页面信息
        $("#emps_teble tbody").empty();
        var emps = result.extend.pageInfo.list;
        $.each(emps, function (index, item) {
            // alert(item.empName);
            var checkBoxTd = $("<td><input type='checkbox' class='check_item'/></td>")
            var enpdTd = $("<td></td>").append(item.empId);
            var empNameId = $("<td></td>").append(item.empName);
            var genderTd = $("<td></td>").append(item.gender == "M" ? "男" : "女");
            var emailTd = $("<td></td>").append(item.email);
            var deptNameTD = $("<td></td>").append(item.department.deptName);


            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append("<span></span>").addClass("glyphicon glyphicon-pencil").append("编辑")
            //为编辑按钮添加一个 自定义的属性 表示当前员工id
            editBtn.attr("edit-id", item.empId);
            var deltBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append("<span></span>").addClass("glyphicon glyphicon-pencil").append("删除")
            deltBtn.attr("del-id", item.empId);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(deltBtn);

            $("<tr></tr>").append(checkBoxTd)
                .append(enpdTd)
                .append(empNameId)
                .append(genderTd)
                .append(emailTd)
                .append(deptNameTD)
                .append(btnTd)
                .appendTo("#emps_teble tbody");
        });
    }

    //分页欣喜
    function build_page_info(result) {
        $("#page_info_area").empty();
        $("#page_info_area").append("当前第" + result.extend.pageInfo.pageNum + "页, 共 "
            + result.extend.pageInfo.pages + " 页,共" + result.extend.pageInfo.total + "条记录");
        totalRcode = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
    }

    function build_page_nav(result) {
        $("#page_nav_area").empty();

        var ul = $("<ul></ul>").addClass("pagination");

        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#")).appendTo("#page_nav_area");
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));

        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));


        if (result.extend.pageInfo.hasPreviousPage == false) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            //为元素添加单击事件
            firstPageLi.click(function () {
                toPage(1);
            })
            prePageLi.click(function () {
                toPage(result.extend.pageInfo.pageNum - 1);
            })
        }


        if (result.extend.pageInfo.hasNextPage == false) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            //为下一页 末页元素添加单击事件
            lastPageLi.click(function () {
                toPage(result.extend.pageInfo.pages);
            })
            nextPageLi.click(function () {
                toPage(result.extend.pageInfo.pageNum + 1);
            })
        }

        ul.append(firstPageLi).append(prePageLi);
        // 导航栏
        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {
            var numLi = $("<li></li>").append($("<a></a>").append(item));
            if (result.extend.pageInfo.pageNum == item) {
                numLi.addClass("active");
            }
            numLi.click(function () {
                toPage(item);
            })
            ul.append(numLi);
        });
        ul.append(nextPageLi).append(lastPageLi);

        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area");
    }

    //清空表单 以及样式
    function reset_form(ele) {
        $(ele)[0].reset();
        //    清空表单样式
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }

    //点击新增按钮 弹出模态框
    $("#empAdd_add_btn").click(function () {

        reset_form("#empAddModel form");
        //发送ajax请求查出部门信息显示在下拉菜单
        getDept("#empAddModel select");
        //打开模态框
        $("#empAddModel").modal({
            //关闭点击背景关闭模态框
            backdrop: "static"
        });
    });

    //点击新增按钮发送ajax请求 显示部门下拉 刘表中
    function getDept(ele) {
        $(ele).empty();
        $.ajax({
            url: "${APP_PATH}/depts",
            type: "GET",
            success: function (result) {
                console.log(result);
                // $("#empAddModel select").append("")
                $.each(result.extend.depts, function () {
                    var option = $("<option></option>").append(this.deptName).attr("value", this.deptId);
                    option.appendTo(ele);
                });
            }
        });
    };

    //表单校验
    function validata_add_form() {
        //        拿到表单数据\
        var empName = $("#empName_add_input").val();
        var refName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u4e00-\u9fa5]{2,5})/;
        if (!refName.test(empName)) {
            // alert("用户名可以是2-5的中文或者6-16位英文和数字的组合");
            show_validata_msg("#empName_add_input", "error", "用户名可以是2-5的中文或者6-16位英文和数字的组合");
            // $("#empName_add_input").parent().addClass("has-error")
            // $("#empName_add_input").next("span").text("用户名可以是2-5的中文或者6-16位英文和数字的组合");
            return false;
        } else {
            show_validata_msg("#empName_add_input", "success", "");
        }
        ;
        var email = $("#email_add_input").val();
        var regEMMail = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
        if (!regEMMail.test(email)) {
            // alert("邮箱格式不正确");
            show_validata_msg("#email_add_input", "error", "邮箱格式不正确");
            return false;
        } else {
            show_validata_msg("#email_add_input", "success", "");
        }

        return true;
    };


    //显示校验信息
    function show_validata_msg(ele, status, msg) {
        //清楚当前元素的教研状态
        $(ele).parent().removeClass("has-success has-error");
        $(ele).next("span").text(" ");
        if ("success" == status) {
            $(ele).parent().addClass("has-success")
            $(ele).next("span").text(msg);
        } else if ("error" == status) {
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    };


    $("#empName_add_input").change(function () {
//发送ajax用户名是否存在校验

        var value = this.value;
        $.ajax({
            url: "${APP_PATH}/checkuse",
            data: "empName=" + value,
            type: "POST",
            success: function (result) {
                if (result.code == 100) {
                    show_validata_msg("#empName_add_input", "success", "用户名可用");
                    $("#save_emp_button").attr("ajax_va", "success");
                } else {
                    show_validata_msg("#empName_add_input", "error", result.extend.va_msg);
                    $("#save_emp_button").attr("ajax_va", "error");
                }
            }
        });
    });
    //点击保存保存员工
    $("#save_emp_button").click(function () {
        //1,对表单进行校验

        if (!validata_add_form()) {
            return false
        };

        if ($(this).attr("ajax_va" ) == "error") {

            return false;
        }
        // 2.发送ajax请求保存员工
        $.ajax({
            url: "${APP_PATH}/emps",
            type: "post",
            data: $("#empAddModel form").serialize(),
            success: function (result) {

                if (result.code == 100) {
                    //  保存成功
                    // 1.关闭模态框
                    $('#empAddModel').modal('hide');
                    //  2.来到最后一页展示数据
                    toPage(totalRcode);
                } else {
                    console.log(result);
                    //    用那个字段的错误信息显示那个
                    if (undefined != result.extend.errorFields.empName) {
                        show_validata_msg("#empName_add_input", "error", result.extend.errorFields.empName);
                    }
                    if (undefined != result.extend.errorFields.email) ;
                    {
                        show_validata_msg("#email_add_input", "error", result.extend.errorFields.email);
                    }
                }
            }
        });
    });


    //    更改绑定淡季事件
    $(document).on("click", ".edit_btn", function () {

        getDept("#empUpdateModel select");
        getEmp($(this).attr("edit-id"));
        $("#update_emp_button").attr("edit-id", $(this).attr("edit-id"));
        $("#empUpdateModel").modal({
            backdrop: "static"
        });
    });

    function getEmp(id) {
        $.ajax({
            url: "${APP_PATH}/emps/" + id,
            type: "GET",
            success: function (result) {
                var emp = result.extend.emp;
                $("#empName_update").text(emp.empName);
                $("#email_update_input").val(emp.email);
                $("#empUpdateModel input[name=gender]").val([emp.gender]);
                $("#empUpdateModel select").val([emp.dId]);
            }
        })
    }


    $("#update_emp_button").click(function () {
        //校验邮箱
        var email = $("#email_update_input").val();
        var regEMMail = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
        if (!regEMMail.test(email)) {
            // alert("邮箱格式不正确");
            show_validata_msg("#email_update_input", "error", "邮箱格式不正确");
            return false;
        } else {
            show_validata_msg("#email_update_input", "success", "");
        }
        // alert($("#empUpdateModel form").serialize());
        $.ajax({
            url: "${APP_PATH}/emps/" + $(this).attr("edit-id"),
            type: "PUT",
            data: $("#empUpdateModel form").serialize(),
            success: function (result) {
                // alert(result.msg)
                //关闭模态框
                $("#empUpdateModel").modal("hide")
                //返回当前页
                toPage(currentPage);
            }
        });
    })

    $(document).on("click", ".delete_btn", function () {
        // alert( $(this).parents("tr").find("td:eq(1)").text())
        var empId = $(this).attr("del-id");
        var empName = $(this).parents("tr").find("td:eq(2)").text();
        if (confirm("确认删除{" + empName + "}吗?")) {
            //     点击确认 发送删除请求
            $.ajax({
                url: "${APP_PATH}/emps/" + empId,
                type: "DELETE",
                success: function (result) {
                    alert(result.msg);
                    //回到本页
                    toPage(currentPage);
                }
            })

        }
    });


    // ?完成全选全不选
    $("#check_all").click(function () {
        $(".check_item").prop("checked", $(this).prop("checked"));
    })
    //
    $(document).on("click", ".check_item", function () {
        var flag = $(".check_item:checked").length == $(".check_item").length;
        $("#check_all").prop("checked", flag);
    })


    //    点击全部删除,部分删除按钮
    $("#del_emp_all_btn").click(function () {

        var empNames = ""
        var del_idstr = ""
        $.each($(".check_item:checked"), function () {
            empNames += $(this).parents("tr").find("td:eq(2)").text()+",";
            del_idstr+= $(this).parents("tr").find("td:eq(1)").text()+"-";
        });

        empNames = empNames.substring(0, empNames.length - 1)
        del_idstr = del_idstr.substring(0, del_idstr.length - 1);
        if (!empNames){
            alert("请勾选要删除的员工");
            return ;
        }

        if (confirm("确认删除{" + empNames + "}吗")) {
            $.ajax({
                url: "${APP_PATH}/emps/" + del_idstr,
                type: "DELETE",
                success: function (result) {
                    alert(result.msg);
                    toPage(currentPage);
                   if ($("#check_all").prop("checked")){
                       $("#check_all ").attr("checked", false);
                   }
                }
            });
        }
    })
</script>
</html>
